package cn.lutu.util.tencentBean;



import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;

@Slf4j
@Component
public class TencentCosUtil {
    @Value("${lutu.tencent.region}")
    private   String region;
    @Value("${lutu.tencent.bucketName}")
    private  String bucketName;
    @Value("${lutu.tencent.secretId}")
    private  String secretId;
    @Value("${lutu.tencent.secretKey}")
    private  String secretKey;
    @Value("${lutu.tencent.url}")
    private  String path;



    public COSClient initCOSClient(){

        /*初始化秘钥信息*/
        COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
        Region region = new Region(this.region);
        /*初始化客户端配置*/
        ClientConfig  clientConfig=new ClientConfig(region);

        /*生成客户端*/
        COSClient cosClient = new COSClient(cred,clientConfig);
        return cosClient;

    }
    /*上传文件*/
    public  String uploadFile(String filePath, File localFile){

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,filePath,localFile);

        COSClient cosClient = initCOSClient();
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

        String pathUrl = path+"/"+filePath;
        return pathUrl;
    }

    /*删除文件*/
    public void delFile(String fileName){
        COSClient cosClient = initCOSClient();
        cosClient.deleteObject(bucketName,fileName);

    }


}
